package org.zhuzx.util;

/**
 * 将JDBC数据类型映射为Java类型的枚举类
 * @author zhuzx 2019年04月30日
 */
public enum JdbcTypes {
	
	ARRAY(null, null),
	BIGINT("Number", "long"),
	BINARY(null, "byte[]"),
	BIT(null, "boolean"),
	BLOB(null, "byte[]"),
	BOOLEAN(null, null),
	CHAR("String", "String"),
	CLOB("String", "String"),
	DATALINK(null, null),
	DATE("Date", "java.sql.Date"),
	DECIMAL("Number", "java.math.BigDecimal"),
	DISTINCT(null, null),
	DOUBLE("Number", "double"),
	FLOAT("Number", "double"),
	INTEGER("Number", "int"),
	JAVA_OBJECT(null, "Object"),
	LONGNVARCHAR(null, null),
	LONGVARBINARY(null, "byte[]"),
	LONGVARCHAR("String", "String"),
	NCHAR(null, null),
	NCLOB(null, null),
	NULL(null, null),
	NUMERIC("Number", "java.math.BigDecimal"),
	NVARCHAR(null, null),
	OTHER(null, "Object"),
	REAL("Number", "float"),
	REF(null, null),
	ROWID(null, null),
	SMALLINT("Number", "int"),
	SQLXML(null, null),
	STRUCT(null, null),
	TIME("Date", "java.sql.Time"),
	TIMESTAMP("Date", "java.sql.Timestamp"),
	TINYINT("Number", "byte"),
	VARBINARY(null, "byte[]"),
	VARCHAR("String", "String");

	private String broadType;
	private String concreteType;
	private JdbcTypes(String broadType, String concreteType) {
		this.broadType = GeneralUtil.getNotBlankString(broadType, "Object");
		this.concreteType = GeneralUtil.getNotBlankString(concreteType, "Object");
	}
	public String getBroadType() {
		return broadType;
	}
	public String getConcreteType() {
		return concreteType;
	}
	
	private static JdbcTypes tryGetValueOf(String dbType) {
		try {
			return JdbcTypes.valueOf(dbType);
		} catch (IllegalArgumentException e) {
			return null;
		}
	}

	/**
	 * 根据JDBC类型判断所属的宽泛类型
	 * @param dbType 标准JDBC类型名
	 * @return String、Number、Date、Object，这四项之一或者null。
	 */
	public static String getBroadType(String dbType) {
		JdbcTypes type = tryGetValueOf(dbType);
		if (type == null) {
			String[] temp = MicroUtil.splitByChar(dbType, ' ');
			if (temp.length > 1) {
				type = JdbcTypes.valueOf(temp[0]);
				if (type == null) {
					type = JdbcTypes.valueOf(temp[1]);
				}
			}
		}
		return (type != null) ? type.getBroadType() : null;
	}

	public static final String BROAD_TYPE_STRING = "String";
	public static final String BROAD_TYPE_NUMBER = "Number";
	public static final String BROAD_TYPE_DATE = "Date";
	public static final String BROAD_TYPE_OBJECT = "Object";
	
}